package com.wxmit.framework.data.permission.core.aspectj;

import com.wxmit.framework.data.permission.core.annotation.DataPermission;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @Description 用于数据权限切面处理
 * @Author huangxiong
 * @Date 2022/7/15 16:38
 * @Version V1.0
 */
@Aspect
public class DataPermissionAspect {

    // 配置织入点
    @Pointcut("@annotation(com.wxmit.framework.data.permission.core.annotation.DataPermission)")
    public void dataPermissionPointCut()
    {
    }

    @Before("dataPermissionPointCut()")
    public void doBefore(JoinPoint point) throws Throwable
    {
        DataPermission dataPermission = getDataPermissionAnn(point);
        if(Objects.nonNull(dataPermission)){
            DataPermissionContextHolder.set(dataPermission);
        }
    }

    @AfterReturning("dataPermissionPointCut()")
    public void doAfter(JoinPoint point)
    {
        DataPermissionContextHolder.clear();
    }

    @AfterThrowing(pointcut = "dataPermissionPointCut()",throwing = "e")
    public void doAfterThrow(JoinPoint joinPoint, Exception e){
        DataPermissionContextHolder.clear();
    }


    /**
     * 是否存在注解，如果存在就获取
     */
    private DataPermission getDataPermissionAnn(JoinPoint joinPoint) throws Exception
    {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null)
        {
            return method.getAnnotation(DataPermission.class);
        }
        return null;
    }
}
